﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

namespace OpenRPOSBackOffice
{
    public partial class Employees : Page
    {
        public string strSelectedName = "";
        public string strSelectedRole = "";

        public Employees()
        {
            InitializeComponent();
        }

        public async void loadRoles()
        {
            Globals.showWaitCursor(true);
            // Load the employee roles...
            cmbRole.Items.Clear();
            await Globals.db.GetRoleObjects("Active=1 order by Title");
            await Globals.db.GetEmployeeRoleObjects("EmployeeID=" + Globals.selectedEmployee.col_ID+" and Active=1");
            foreach (ServiceReferenceOpenRPOS.EmployeeRole employeeRole in Globals.db.EmployeeRoleRecords)
                foreach(ServiceReferenceOpenRPOS.Role role in Globals.db.RoleRecords)
                    if (employeeRole.col_RoleID == role.col_ID)
                    {
                        cmbRole.Items.Add(role.col_Title);
                    }
            // Set the selected role...
            if (cmbRole.Items.Count > 0)
            {
                if (strSelectedRole == "")
                    cmbRole.SelectedIndex = 0;
                else
                {
                    cmbRole.SelectedValue = strSelectedRole;
                    strSelectedRole = "";
                }
            }
            else
            {
                tbRate.Text = "";
                btnRemoveRole.IsEnabled = false;
            }
            Globals.showWaitCursor(false);
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        // Executes when the user navigates to this page.
        public async void init()
        {
            Globals.showWaitCursor(true);
            // Ensure private data is initially collapsed...
            expPersonalInformation.IsExpanded = false;
            expEmploymentData.IsExpanded = false;
            // Only enable "restore" button if there are employees to restore
            await Globals.db.GetEmployeeObjects("Active=0 order by LastName, FirstName, MiddleInitial");
            btnRestore.IsEnabled = Globals.db.EmployeeRecords.Count > 0;
            cmbEmployeeName.Items.Clear();
            // Load employee names into the drop-down box
            if (await Globals.db.GetEmployeeObjects("Active=1 order by LastName, FirstName, MiddleInitial"))
            {
                foreach (ServiceReferenceOpenRPOS.Employee emp in Globals.db.EmployeeRecords)
                {
                    cmbEmployeeName.Items.Add(emp.col_LastName + ", " + emp.col_FirstName + " " + emp.col_MiddleInitial);
                }
                if (cmbEmployeeName.Items.Count > 0)
                {
                    if (strSelectedName == "")
                        cmbEmployeeName.SelectedIndex = 0;
                    else
                    {
                        cmbEmployeeName.SelectedValue = strSelectedName;
                        strSelectedName = "";
                    }
                }
            }
            if (cmbEmployeeName.Items.Count > 0) cmbEmployeeName.SelectedIndex = 0;
            Globals.employees = this;
            Globals.showWaitCursor(false);
        }

        private void btnChangePassword_Click(object sender, RoutedEventArgs e)
        {
            // Prompt the user to update their password....
            NewPasswordDialog npd = new NewPasswordDialog();
            npd.Show();
        }

        private async void cmbEmployeeName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbEmployeeName.Items.Count > 0)
            {
                Globals.showWaitCursor(true);
                if(cmbEmployeeName.SelectedIndex<0) cmbEmployeeName.SelectedIndex = 0;
                // Populate personal information
                Globals.selectedEmployee = Globals.db.EmployeeRecords[cmbEmployeeName.SelectedIndex];
                tbStreetAddress.Text = Globals.selectedEmployee.col_Address1;
                tbAdditionalAddress.Text = Globals.selectedEmployee.col_Address2;
                tbCity.Text = Globals.selectedEmployee.col_City;
                tbState.Text = Globals.selectedEmployee.col_State;
                tbZip.Text = Globals.selectedEmployee.col_Zip;
                tbHomePhone.Text = Regex.Replace(Globals.selectedEmployee.col_HomePhone, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
                tbCellPhone.Text = Regex.Replace(Globals.selectedEmployee.col_CellPhone, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
                tbEmail.Text = Globals.selectedEmployee.col_Email;
                tbSSN.Text = Regex.Replace(Globals.selectedEmployee.col_SSN, @"(\d{3})(\d{2})(\d{4})", "$1-$2-$3");
                // Populate employment information
                await Globals.db.GetLoginObjects("ID=" + Globals.selectedEmployee.col_LoginID.ToString());
                Globals.selectedLogin = Globals.db.LoginRecords[0];
                tbLoginID.Text = Globals.selectedLogin.col_UserName;
                tbDisplayName.Text = Globals.selectedLogin.col_DisplayName;
                cbManager.IsChecked = Globals.selectedLogin.col_Manager;
                // Fill-in roles/rates
                loadRoles();
                Globals.showWaitCursor(false);
            }
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            // Add a new employee
            AddEmployeeDialog aed = new AddEmployeeDialog();
            aed.Show();
        }

        private async void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            // Get confirmation before deactivating...
            if (MessageBox.Show("Are you sure you want to remove the selected employee?","Confirm",MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                // Flag selected employee as unavailable
                Globals.selectedEmployee.col_Active = false;
                Globals.selectedEmployee.bFilterActive = true;
                await Globals.db.UpdateEmployeeObject(Globals.selectedEmployee);
                // Re-load the employee list
                strSelectedName = "";
                init();
            }
        }

        private void btnRestore_Click(object sender, RoutedEventArgs e)
        {
            RestoreEmployeeDialog red = new RestoreEmployeeDialog();
            red.Show();
        }

        private async void btnNewRole_Click(object sender, RoutedEventArgs e)
        {
            Globals.showWaitCursor(true);
            AddRoleDialog ard = new AddRoleDialog();
            await ard.loadRoles();
            ard.employee = this;
            Globals.showWaitCursor(false);
            ard.Show();
        }

        private void cmbRole_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbRole.Items.Count > 0)
            {
                if (cmbRole.SelectedIndex < 0) cmbRole.SelectedIndex = 0;
                if (Globals.db.EmployeeRoleRecords.Count > 0) tbRate.Text = Globals.db.EmployeeRoleRecords[cmbRole.SelectedIndex].col_Rate.ToString("C");
                btnRemoveRole.IsEnabled = true;
            }
        }

        private async void btnRemoveRole_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Are you sure that you want to remove the selected role for this user?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                // Remove the selected role for this user
                Globals.db.EmployeeRoleRecords[cmbRole.SelectedIndex].bFilterActive = true;
                Globals.db.EmployeeRoleRecords[cmbRole.SelectedIndex].col_Active = false;
                await Globals.db.UpdateEmployeeRoleObject(Globals.db.EmployeeRoleRecords[cmbRole.SelectedIndex]);
                // Re-load the roles...
                loadRoles();
            }
        }

        private async void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            // Confirm the update
            if (MessageBox.Show("Are you sure you want to update this information?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                // Update modified fields
                Globals.showWaitCursor(true);
                // Check street address
                if (Globals.selectedEmployee.col_Address1 != tbStreetAddress.Text)
                {
                    Globals.selectedEmployee.bFilterAddress1 = true;
                    Globals.selectedEmployee.col_Address1 = tbStreetAddress.Text;
                }
                else
                    Globals.selectedEmployee.bFilterAddress1 = false;
                // Check additional address
                if (Globals.selectedEmployee.col_Address2 != tbAdditionalAddress.Text)
                {
                    Globals.selectedEmployee.bFilterAddress2 = true;
                    Globals.selectedEmployee.col_Address2 = tbAdditionalAddress.Text;
                }
                else
                    Globals.selectedEmployee.bFilterAddress2 = false;
                // Check city
                if (Globals.selectedEmployee.col_City != tbCity.Text)
                {
                    Globals.selectedEmployee.bFilterCity = true;
                    Globals.selectedEmployee.col_City = tbCity.Text;
                }
                else
                    Globals.selectedEmployee.bFilterCity = false;
                // Check state
                if (Globals.selectedEmployee.col_State != tbState.Text)
                {
                    Globals.selectedEmployee.bFilterState = true;
                    Globals.selectedEmployee.col_State = tbState.Text;
                }
                else
                    Globals.selectedEmployee.bFilterState = false;
                // Check zip
                if (Globals.selectedEmployee.col_Zip != tbZip.Text)
                {
                    Globals.selectedEmployee.bFilterZip = true;
                    Globals.selectedEmployee.col_Zip = tbZip.Text;
                }
                else
                    Globals.selectedEmployee.bFilterZip = false;
                // Check SSN
                if (Globals.selectedEmployee.col_SSN != Globals.reDigits.Replace(tbSSN.Text, ""))
                {
                    Globals.selectedEmployee.bFilterSSN = true;
                    Globals.selectedEmployee.col_SSN = Globals.reDigits.Replace(tbSSN.Text, "");
                    tbSSN.Text = Regex.Replace(Globals.selectedEmployee.col_SSN, @"(\d{3})(\d{2})(\d{4})", "$1-$2-$3");
                }
                else
                    Globals.selectedEmployee.bFilterSSN = false;
                // Check home phone
                if (Globals.selectedEmployee.col_HomePhone != Globals.reDigits.Replace(tbHomePhone.Text, ""))
                {
                    Globals.selectedEmployee.bFilterHomePhone = true;
                    Globals.selectedEmployee.col_HomePhone = Globals.reDigits.Replace(tbHomePhone.Text, "");
                    tbHomePhone.Text = Regex.Replace(Globals.selectedEmployee.col_HomePhone, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
                }
                else
                    Globals.selectedEmployee.bFilterHomePhone = false;
                // Check cell phone
                if (Globals.selectedEmployee.col_CellPhone != Globals.reDigits.Replace(tbCellPhone.Text, ""))
                {
                    Globals.selectedEmployee.bFilterCellPhone = true;
                    Globals.selectedEmployee.col_CellPhone = Globals.reDigits.Replace(tbCellPhone.Text, "");
                    tbCellPhone.Text = Regex.Replace(Globals.selectedEmployee.col_CellPhone, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
                }
                else
                    Globals.selectedEmployee.bFilterCellPhone = false;
                // Check e-mail
                if (Globals.selectedEmployee.col_Email != tbEmail.Text)
                {
                    Globals.selectedEmployee.bFilterEmail = true;
                    Globals.selectedEmployee.col_Email = tbEmail.Text;
                }
                else
                    Globals.selectedEmployee.bFilterEmail = false;
                // Update rate for the selected role
                if (cmbRole.SelectedIndex >= 0 && Globals.db.EmployeeRoleRecords.Count > 0)
                {
                    tbRate.Text = Globals.reDigits.Replace(tbRate.Text, "");
                    if (tbRate.Text.Length > 4) tbRate.Text = tbRate.Text.Substring(0, 4);
                    if (tbRate.Text.Length == 0) tbRate.Text = "0";
                    Globals.db.EmployeeRoleRecords[cmbRole.SelectedIndex].bFilterRate = true;
                    Globals.db.EmployeeRoleRecords[cmbRole.SelectedIndex].col_Rate = Convert.ToDecimal(tbRate.Text) / 100;
                    tbRate.Text = Globals.db.EmployeeRoleRecords[cmbRole.SelectedIndex].col_Rate.ToString("C");
                    await Globals.db.UpdateEmployeeRoleObject(Globals.db.EmployeeRoleRecords[cmbRole.SelectedIndex]);
                }
                // Update login information
                Globals.selectedLogin.col_UserName = tbLoginID.Text;
                Globals.selectedLogin.bFilterUserName = true;
                Globals.selectedLogin.col_DisplayName = tbDisplayName.Text;
                Globals.selectedLogin.bFilterDisplayName = true;
                Globals.selectedLogin.col_Manager = (bool)cbManager.IsChecked;
                Globals.selectedLogin.bFilterManager = true;
                // Perform the update...
                await Globals.db.UpdateEmployeeObject(Globals.selectedEmployee);
                await Globals.db.UpdateLoginObject(Globals.selectedLogin);
                // If the update was made to the current, update that as well
                if (Globals.selectedEmployee.col_ID == Globals.currentEmployee.col_ID)
                {
                    Globals.currentEmployee = Globals.selectedEmployee;
                    Globals.currentLogin = Globals.selectedLogin;
                    Globals.mainPage.lblUsername.Content = "User: " + Globals.currentLogin.col_DisplayName;
                }
                // Prompt the user
                Globals.showWaitCursor(false);
                MessageBox.Show("Information has been updated.");
            }
        }

        private void btnEditName_Click(object sender, RoutedEventArgs e)
        {
            // Present a dialog to update the selected user name...
            EditEmployeeNameDialog eend = new EditEmployeeNameDialog();
            eend.Show();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            init();
        }
    }
}
